<template>
  <div>
    <el-button
      type="danger"
      @click="showEditForm('add')"
      v-if="userInfo.roleType === 1"
      >新增专题</el-button
    >
    <el-row :gutter="10" :style="{ 'margin-top': '10px' }">
      <el-col :span="14">
        <el-card class="box-card">
          <template #header>
            <span>专题</span>
          </template>
          <Table
            :columns="columns"
            :showPagination="true"
            :dataSource="tableData"
            :fetch="loadDataList"
            :options="tableOptions"
            row-key="categoryId"
            @row-click="loadSpecialTree"
            ref="tableDataRef"
            v-show="isVisible"
          >
            <template #cover="{ index, row }">
              <Cover :cover="row.cover"></Cover>
            </template>
            <template #op="{ index, row }" v-if="userInfo.rowType === 1">
              <div class="op">
                <a
                  href="javascript:void(0)"
                  class="a-link"
                  @click="showEditForm('update', row)"
                  >修改</a
                >
                <el-divider direction="vertical" />
                <a
                  href="javascript:void(0)"
                  class="a-link"
                  @click="delCategory(row)"
                  >删除</a
                >
              </div>
            </template>
          </Table>
        </el-card>
      </el-col>
      <el-col :span="10">
        <el-card class="box-card">
          <template #header>
            <span>专题文章</span>
          </template>
          <div :style="{ 'margin-bottom': '5px' }">
            <el-alert
              title="红色-草稿，绿色-已发布，拖动文章修改排序"
            ></el-alert>
          </div>
          <div class="special-blog-tree">
            <el-tree
              class="tree-panel"
              ref="refTree"
              :data="blogList"
              default-expand-all
              node-key="blogId"
              :expand-on-click-node="false"
              :props="treeProps"
              :highlight-current="true"
              :row-class-name="tableRowClassName"
              draggable
              @node-drop="blogDrag"
            >
              <template #default="{ node, data }">
                <span class="custom-node-style">
                  <!-- {{ data }} -->
                  <span class="node-title">
                    <span v-if="data.status == 0" :style="{ color: 'red' }">{{
                      data.title
                    }}</span>
                    <span v-else :style="{ color: 'green' }">{{
                      data.title
                    }}</span>
                  </span>
                  <!-- {{data}} -->
                  <span class="node-op">
                    <template v-if="data.blogId === '0'">
                      <a
                        class="a-link"
                        href="javascript:void(0)"
                        @click="editBlog('add', data)"
                        >新增文章</a
                      >
                    </template>
                    <template v-else>
                      <a
                        class="a-link"
                        href="javascript:void(0)"
                        @click="showDetail(data)"
                        >预览</a
                      >
                      <el-divider direction="vertical" />
                      <a
                        :class="
                          userInfo.roleType === 1 ||
                          data.userId === userInfo.userId
                            ? 'a-link'
                            : 'disabled-link'
                        "
                        href="javascript:void(0)"
                        @click="editBlog('edit', data)"
                        >修改</a
                      >
                      <el-divider direction="vertical" />
                      <a
                        :class="
                          userInfo.roleType === 1 ||
                          data.userId === userInfo.userId
                            ? 'a-link'
                            : 'disabled-link'
                        "
                        href="javascript:void(0)"
                        @click="delBlog(data)"
                        >删除</a
                      >
                      <el-divider direction="vertical" />
                      <a
                        class="a-link"
                        href="javascript:void(0)"
                        @click="editBlog('add', data)"
                        >新增下级文章</a
                      >
                    </template>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <Dialog
      :show="dialogConfig.show"
      :title="dialogConfig.title"
      :buttons="dialogConfig.buttons"
      @close="dialogConfig.show = false"
      ><el-form :model="formData" :rules="rules" ref="formDataRef">
        <el-form-item prop="categoryId" v-model.trim="formData.categoryId">
        </el-form-item>
        <el-form-item prop="categoryName" label="名称 ">
          <el-input
            placeholder="请输入分类名称"
            v-model.trim="formData.categoryName"
            size="large"
          >
          </el-input>
        </el-form-item>
        <el-form-item prop="cover" label="封面 ">
          <CoverUpload v-model="formData.cover"></CoverUpload>
        </el-form-item>
        <el-form-item prop="categoryDesc" label="简介 ">
          <el-input
            placeholder="请输入分类介绍"
            v-model.trim="formData.categoryDesc"
            type="textarea"
            :autosize="{ minRows: 4, maxRows: 4 }"
            size="large"
          >
          </el-input>
        </el-form-item> </el-form
    ></Dialog>
    <BlogEdit ref="blogEditRef" @callback="saveBlogCallback"></BlogEdit>
    <BlogDetail ref="blogDetailRef" @callback="saveBlogCallback"></BlogDetail>
  </div>
</template>

<script setup>
import BlogEdit from "./BlogEdit.vue";
import BlogDetail from "./BlogDetail.vue";
import { getCurrentInstance, nextTick, reactive, ref } from "vue";
import { ElMessage } from "element-plus";

const { proxy } = getCurrentInstance();
const userInfo = ref(proxy.VueCookies.get("userInfo"));
const api = {
  loadDataList: "/category/loadCategory4Special",
  saveCategory: "category/saveCategory4Special",
  delCategory: "/category/delCategory4Special",
  getSpecialInfo: "/blog/getSpecialInfo",
  delBlog: "/blog/recoveryBlog",
  updateSpecialBlogSort: "/blog/updateSpecialBlogSort",
};
const columns = [
  {
    label: "封面",
    prop: "cover",
    width: 80,
    scopedSlots: "cover",
  },
  {
    label: "名称",
    prop: "categoryName",
    width: 200,
  },
  {
    label: "简介",
    prop: "categoryDesc",
  },
  {
    label: "博客数量",
    prop: "blogCount",
    width: 80,
  },
  {
    label: "操作",
    prop: "op",
    width: 120,
    scopedSlots: "op",
  },
];
const isVisible = ref(true);

// 获取所有专题
const tableDataRef = ref();
const currentCategoryId = ref(null);
const tableData = reactive({});
const tableOptions = { extHeight: 120 };
const loadDataList = async (rowData) => {
  // console.log(rowData === undefined);
  // console.log(rowData);
  let result = await proxy.Request({
    url: api.loadDataList,
  });
  if (!result) {
    return;
  }
  // console.log(result.data);
  // console.log(result.data);
  // tableData.list = result.data;
  // 文档里描述的是错的，返回的和分类的是不同的
  Object.assign(tableData, result.data);
  if (currentCategoryId.value == null && result.data.list.length > 0) {
    currentCategoryId.value = result.data.list[0].categoryId;
  }
  // console.log(currentCategoryId.value);
  nextTick(() => {
    // tableDataRef.value.setCurrentRow(tableData.list[3].categoryId);
    // for (const item of tableData.list) {
    //   if (item.categoryId === 10038) {
    //     console.log(item.categoryId);
    //     this.$refs.filedNameTable.setCurrentRow(item)
    //   }
    // }
    // console.log(rowData === undefined);
    if (rowData === undefined) {
      // currentCategoryId.value = tableData.list[3].categoryId;

      loadSpecialTree(tableData.list[0]);
    } else {
      currentCategoryId.value = rowData.categoryId;
      loadSpecialTree(rowData);
    }
  });
};
const dialogConfig = reactive({
  show: false,
  title: "标题",
  buttons: [
    {
      type: "danger",
      text: "确定",
      click: (e) => {
        submitForm();
      },
    },
  ],
});

// 分类表单填写
const formData = reactive({});
const rules = {};
const formDataRef = ref();
//新增、编辑分类
const showEditForm = (type, data) => {
  dialogConfig.show = true;
  nextTick(() => {
    formDataRef.value.resetFields();

    if (type == "add") {
      dialogConfig.title = "新增分类";
    } else if (type == "update") {
      dialogConfig.title = "编辑分类";
      Object.assign(formData, data);
      console.log(data);
      // console.log(formData);
    }
  });
};
const submitForm = () => {
  formDataRef.value.validate(async (valid) => {
    if (!valid) {
      return;
    }
    let params = {};
    Object.assign(params, formData);
    let result = await proxy.Request({
      url: api.saveCategory,
      params,
    });
    if (!result) {
      return;
    }
    dialogConfig.show = false;
    // Object.keys(formData).forEach((key) => {
    //   formData[key] = "";
    // });
    console.log(formData);
    ElMessage.success("保存成功");
    loadDataList();
  });
};

const delCategory = (data) => {
  proxy.Confirm(`你去定要删除${data.categoryName}`, async () => {
    let result = await proxy.Request({
      url: api.delCategory,
      params: {
        categoryId: data.categoryId,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
    ElMessage.success("删除成功");
  });
};

// 专题树
// 属性展示专题
const treeProps = {
  children: "children",
  label: "title",
  value: "blogId",
};

const blogList = ref({});

// 获取专题文章树
// 行点击事件默认就会带有行的信息
const loadSpecialTree = async (data) => {
  // console.log(data);
  // tableDataRef.value.setCurrentRow(data);
  let categoryId = data.categoryId;
  let result = await proxy.Request({
    url: api.getSpecialInfo,
    params: {
      categoryId: categoryId,
      showType: 1,
    },
  });
  if (!result) return;
  blogList.value = result.data;
  ElMessage.success("获取专题成功");
};

// 新增，修改专题博客
const blogEditRef = ref(null);
const editBlog = (type, data) => {
  isVisible.value = false;
  blogEditRef.value.init(type, data);
};
const saveBlogCallback = (data) => {
  isVisible.value = true;
  nextTick(() => {
    console.log(data);
    loadSpecialTree(data);
  });
};

// 刪除博客
const delBlog = (data) => {
  proxy.Confirm(`你確定要删除[${data.title}]嗎？`, async () => {
    let result = await proxy.Request({
      url: api.delBlog,
      params: {
        blogId: data.blogId,
      },
    });
    if (!result) {
      return;
    }
    loadDataList();
    ElMessage.success("博客删除成功");
  });
};

const blogDetailRef = ref(null);
const showDetail = (data) => {
  blogDetailRef.value.init(data);
  isVisible.value = false;
};

// 高亮某一行
const highlightedId = ref(null);
const tableRowClassName = ({ row }) => {
  console.log(row);
  if (row.categoryId === highlightedId.value) {
    return "highlight-row";
  }
  return "";
};

// 拖动改变排序，修改父级
const blogDrag = async (draggingNode, dropNode, dropType, ev) => {
  console.log("tree drop:", dropNode.label, dropType);
  let parentNode = null;
  if (dropType == "inner") {
    parentNode = dropNode;
  } else {
    parentNode = dropNode.parent;
  }
  // 操作节点的ID
  const blogId = draggingNode.data.blogId;
  const pBlogId = parentNode.data.blogId;
  // 需要重新排序的博客ID
  const blogIds = [];
  parentNode.childNodes.forEach((element) => {
    blogIds.push(element.data.blogId);
  });
  let params = {
    blogId,
    pBlogId,
    blogIds: blogIds.join(","),
  };
  let result = await proxy.Request({
    url: api.updateSpecialBlogSort,
    params,
  });
  if (!result) {
    return;
  }
  // 重新加载文章树？
};
</script>

<style lang="scss" scoped>
.special-blog-tree {
  height: calc(100vh - 235px - 43px);
}

.special-blog-tree :deep(.custom-node-style) {
  flex: 1;
  display: flex;
  justify-content: space-between;
}
.custom-node-style {
  display: flex;
}

.highlight-row {
  background-color: #628ce0; /* 你可以根据需要调整高亮的样式 */
}
</style>
